let ApigwClient = require('./indexToken');
var {createHmac} = require('crypto');

class KingdeeAuthToken {

    /**
     * 构造器
     */
    constructor(params) {
        this.clientID = params.clientID;
        this.clientSecret = params.clientSecret;
        this.appKey = params.appKey;
        this.outerInstanceId = params.outerInstanceId;
    }

    /**
     * 主动获取授权
     */
    async pushAppAuthorize() {
        let list;
        try {
            let requestSDK = new ApigwClient(this.clientID, this.clientSecret);
            const api = 'https://api.kingdee.com/jdyconnector/app_management/push_app_authorize';
            const resp = await requestSDK.request({
                url: api,
                method: 'post',
                params: {
                    outerInstanceId: this.outerInstanceId,
                },
            });
            console.log('主动获取授权msg', resp.data.msg);
            list = resp.data.data[0];
        } catch (e) {
            console.error('主动获取授权', e);
        }
        return list;
    }

    /**
     * 获取app-token
     */
    async getAppToken() {
        let list;
        try {
            let {sign, pushAppAuthorizeList} = await this.appSignature();
            let requestSDK = new ApigwClient(this.clientID, this.clientSecret);
            const api = 'https://api.kingdee.com/jdyconnector/app_management/kingdee_auth_token';
            const resp = await requestSDK.request({
                // 调用api获取app-token
                url: api,
                method: 'get',
                params: {
                    app_key: this.appKey,
                    app_signature: sign
                },
            });
            console.log('获取app-token', resp.data.description);
            list = {
                pushAppAuthorizeList,
                appTokenList: resp.data.data
            };
        } catch (e) {
            console.error('获取app-token', e);
        }
        return list;
    }

    /**
     * 获取app_signature
     */
    async appSignature() {
        let list;
        let sign;
        const appKey = this.appKey;
        const pushAppAuthorizeList = await this.pushAppAuthorize();
        let sha256 = createHmac('sha256', pushAppAuthorizeList.appSecret);
        sha256.update(appKey);
        sign = Buffer.from(sha256.digest('hex'), 'utf8').toString('base64');
        list = {sign, pushAppAuthorizeList};
        return list;
    }
}

module.exports = KingdeeAuthToken;
